package com.cac.demo.controller.gkinterface;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cac.demo.dao.outBill.ReturnApplyDao;
import com.cac.demo.dao.outBill.WmsInvOutBillHDao;
import com.cac.demo.service.gkinterface.ErpBackAsync;
import com.cac.demo.service.gkinterface.WorkService;
import com.cac.demo.service.materialScan.WmsDeliverPlanService;
import com.cac.demo.service.outBill.WmsInvOutBillService;
import com.cac.demo.util.CreatMsgId;
import com.cac.demo.util.ExceptionToStirng;
import com.cac.demo.util.adapter.ComUtil;
import com.cac.demo.util.adapter.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: ErpToWmsBDataRest
 * @description: （纯字符串调用）
 * @author:
 * @date: 2023/3/3 9:27:27 周五
 * @version: 1.0
 */
@RestController
@RequestMapping("/ErpToWms")
@Slf4j
public class ErpToWmsBDataRest {

    @Autowired
    private WmsDeliverPlanService wmsDeliverPlanService;
    @Autowired
    private WorkService workService;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private WmsInvOutBillService wmsInvOutBillService;
    @Autowired
    private Environment environment;
    @Autowired
    private WmsInvOutBillHDao wmsInvOutBillHDao;
    @Autowired
    private ErpBackAsync erpBackAsync;
    @Autowired
    private ReturnApplyDao returnApplyDao;

    @PostMapping("/delConfirm")
    public ResponseMsg<String> delConfirm(@RequestBody String BData) {
        String func = null;
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        //获取参数BData
//        String BData = (String) hashMap.get("BData");
        log.info("园区网下发工控网文件流接收测试，时间：" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));


        JSONArray paramJsonObjectArray = new JSONArray();
        String LogId = ComUtil.getId();
        //2023-06-17 yebo 新增日志表，可作用于防止网闸短时间内重复调用
        HashMap logMap = new HashMap();
        logMap.put("msErpExchangeLogId", LogId);
        //判断参数
        if (BData != null || "".equals(BData)) {
            //事务管理
            TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
            //解密参数，转为字符串
            String decodedBytes = new String();
            try {
                decodedBytes = Base64.decodeStr(BData, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String DeBData = decodedBytes;
            if (DeBData.length() > 200) {
                log.info("delConfirm==================业务参数BData:" + DeBData.substring(0, 200));
            } else {
                log.info("delConfirm=================业务参数BData:" + DeBData);
            }
            //字符串转为JSON对象
            JSONObject paraJsonObject = JSONObject.parseObject(DeBData);
            //获取func 和param
            func = paraJsonObject.getString("func");
            String param = paraJsonObject.getString("param");
            paramJsonObjectArray = JSONArray.parseArray(param);
            HashMap map;
            HashMap issuedTest = new HashMap();
            String rstl = "";

            //记录园区网下发日志
            issuedTest.put("id", LogId);
            issuedTest.put("BData", DeBData);
            issuedTest.put("type", func);
            issuedTest.put("msgId", paraJsonObject.get("msgId"));
            //2023-06-17 yebo 保存日志信息新
          /*  logMap.put("func", func);
            logMap.put("msgId", paraJsonObject.get("msgId"));
            workService.insertErpLog(logMap);
            logMap.put("bdata", DeBData);
            workService.updateErpBdata(logMap);*/

            try {
                issuedTest.put("nowTime", com.cac.demo.util.DateUtil.nowTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            log.info("=======================园区网下发===============================");
            try {
                //成品删除预上账
                if (func != null && "ERP-101-delConfirmCp".equals(func)) {
                    log.info("成品删除预上账");
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        //修改交接单
                        int result = wmsDeliverPlanService.updateDeleteCpAdvancePosting(map);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", map.get("wms_delivery_plan_id"));
                        responseMsg.setRetCode("200").setMessage("删除成功！");
                    }
                    //零件删除预上账
                } else if (func != null && "ERP-101-delConfirmLj".equals(func)) {
                    log.info("零件删除预上账");
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        //修改交接单
                        int result = wmsDeliverPlanService.updateDeleteLjAdvancePosting(map);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", map.get("wms_delivery_plan_id"));
                        responseMsg.setRetCode("200").setMessage("删除成功！");
                    }
                }   //标准件删除预上账
                else if (func != null && "ERP-101-delConfirmBzj".equals(func)) {
                    log.info("标准件删除预上账");
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        //修改交接单
                        int result = wmsDeliverPlanService.updateDeleteBLjAdvancePosting(map);
                        responseMsg.setRetCode("200").setMessage("删除成功！");
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", map.get("wms_delivery_plan_id"));
                    }
                }

                //ERP出库占用
                else if (func != null && "ERP-101-InvOutAllot".equals(func)) {
                    log.info("ERP出库占用");
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        map.put("func", func);
                        int cnt = wmsInvOutBillService.searchItemInventoryExists(map);
                        if (cnt == 0) {
                            issuedTest.put("remark", "not_exists");
                            continue;
                        }
                        //出库占用
                        wmsInvOutBillService.erpOutOccupyAllotment(map);
                        //出库占用更新台账表数量 yebo 同步厂内修改
                        wmsInvOutBillService.erpUpdateInventory(map);
                        //插入出库申请主表
                        wmsInvOutBillService.erpOutOccupyOutBillH(map);
                        //插入出库申请子表
                        wmsInvOutBillService.erpOutOccupyOutBillL(map);
                        responseMsg.setResponseBody("成功");
                        issuedTest.put("businessTab", "wms_inv_out_allotment");
                        issuedTest.put("businessCol", "wms_inv_out_allotment_id");
                        issuedTest.put("businessVal", map.get("wmsInvOutAllotmentId"));

                    }
                }
                //ERP占用取消
                else if (func != null && "ERP-101-InvOutAllotCancel".equals(func)) {
                    log.info("ERP出库占用取消");
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        map.put("func", func);
                        //1.判断有无出库信息
                        String isTransAllot = wmsInvOutBillHDao.isTransAllot(map);
                        //没有出库信息
                        if (isTransAllot.equals("0")) {
                            //3.判断有无出库占用信息
                            String isOutAllot = wmsInvOutBillHDao.isOutAllot(map);
                            if (isOutAllot.equals("0")) {
                                throw new Exception("无出库占用信息,请重新下发出库占用");
                            }
                        }
                        //有出库信息
                        else {
                            //2.判断有无出库撤销信息
                            String isOutCancel = wmsInvOutBillHDao.isOutCancel(map);
                            if (isOutCancel.equals("0")) {
                                throw new Exception("无出库撤销信息,请重新下发出库撤销");
                            }
                        }
                        //出库占用取消
                        wmsInvOutBillService.InvOutAllotCancel(map);
                        issuedTest.put("businessTab", "wms_inv_out_allotment");
                        issuedTest.put("businessCol", "wms_inv_out_allotment_id");
                        issuedTest.put("businessVal", map.get("wmsInvOutAllotmentId"));
                    }
                }
                //ERP出库
                else if (func != null && "ERP-101-InvOut".equals(func)) {
                    log.info("ERP出库流水信息");
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        map.put("func", func);
                        //1:判断出库主表 无 throw new Exception("出库占用信息不存在");
                        String isOutBillH = wmsInvOutBillHDao.isOutBillH(map);
                        if (isOutBillH.equals("0")) {
                            throw new Exception("出库占用信息不存在");
                        }
                        //2:判断流水表 有  throw new Exception("出库流水已经存在");
                        String isTransAllot = wmsInvOutBillHDao.isTransAllot(map);
                        if (!isTransAllot.equals("0")) {
                            throw new Exception("出库流水已经存在,请勿重复出库");
                        }
                        int cnt = wmsInvOutBillService.searchItemInventoryExists(map);
                        if (cnt == 0) {
                            issuedTest.put("remark", "not_exists");
                            continue;
                        }
                        //出库操作流水表 台账表
                        wmsInvOutBillService.erpOutOccupyTransaction(map);
                        issuedTest.put("businessTab", "wms_inv_out_allotment");
                        issuedTest.put("businessCol", "wms_inv_out_allotment_id");
                        issuedTest.put("businessVal", map.get("wmsInvOutAllotmentId"));
                    }
                }
                //ERP出库撤销
                else if (func != null && "ERP-101-InvOutCancel".equals(func)) {
                    log.info("ERP出库流水信息");
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        map.put("func", func);
                        String isTransOut = wmsInvOutBillHDao.isTransOut(map);
                        //没有出库信息
                        if (isTransOut.equals("0")) {
                            throw new Exception("无出库信息,请重新下发出库");
                        }
                        //出库撤销操作流水表
                        wmsInvOutBillService.erpOutOccupyCancel(map);
                        issuedTest.put("businessTab", "wms_inv_out_allotment");
                        issuedTest.put("businessCol", "wms_inv_out_allotment_id");
                        issuedTest.put("businessVal", map.get("wmsInvOutAllotmentId"));
                    }
                }
                //wms查询ERP返回erp处理结果
                else if (func != null && "ERP-101-RCVMSG".equals(func)) {
                    log.info("异步执行==================ERP-101-RCVMSG========start===========");
                    //workService.resultBackToWms(paramJsonObjectArray, (String) paraJsonObject.get("msgId"), func);
                    erpBackAsync.resultBackToWmsAsync(paramJsonObjectArray, (String) paraJsonObject.get("msgId"), func);
                    log.info("异步执行==================ERP-101-RCVMSG========end===========");
                }
                //ERP主动查询101处理结果
                else if (func != null && "ERP-101-MSGSTATUS".equals(func)) {
                    String openMsgStatus = environment.getProperty("pathProperty.openMsgStatus");
                    if ("true".equals(openMsgStatus)) {//开关控制
                        //查询是否ERP半个小时内是否已经发起过,未发起才执行
                        //    if (workService.queryIsRepeat(logMap)) {
                        String msgId = CreatMsgId.getMsgId();
                        log.info("异步执行=================ERP-101-MSGSTATUS========start===========");
                        //workService.resultBackToErp(paramJsonObjectArray, msgId);
                        if (paramJsonObjectArray.size() > 1200) {

                        } else {
                            erpBackAsync.resultBackToErpAsync(paramJsonObjectArray, msgId);
                        }
                        log.info("异步执行==================ERP-101-MSGSTATUS========end===========");
                        //    }
                    }
                    if (issuedTest.get("BData").toString().length() > 100) {//截取日志存放内容，防止刷屏日志
                        issuedTest.put("BData", issuedTest.get("BData").toString().substring(0, 100));
                    }
                } else if (func != null && "ERP-101-returnApplyReceived".equals(func)) {
                    //接收ERP 退库反馈信息
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        Map tmp = JSON.parseObject(paramJsonObjectArray.get(i).toString(), Map.class);
                        returnApplyDao.updateReturnApplyErpFeedBack(tmp);
                    }
                }
                platformTransactionManager.commit(transaction);
                issuedTest.put("result", "操作成功");
                issuedTest.put("retCode", "1");
                rstl = "操作成功";
            } catch (DuplicateKeyException ex) {
                platformTransactionManager.rollback(transaction);
                rstl = "操作成功,当前数据已经接收！请不要重复传递";
                logMap.put("wmsResult", rstl);
                issuedTest.put("result", rstl);
                issuedTest.put("retCode", "1");
            } catch (Exception e) {
                e.printStackTrace();
                rstl = ExceptionToStirng.getExceptionToString(e);
                logMap.put("wmsResult", rstl);
                if (rstl.length() > 200) {
                    rstl = rstl.substring(0, 200);
                }
                issuedTest.put("result", rstl);
                issuedTest.put("retCode", "0");
                responseMsg.setMessage("接收失败！失败原因：" + e.getMessage());
                platformTransactionManager.rollback(transaction);
            } finally {
                issuedTest.put("failMsg", rstl);
                issuedTest.put("system", "ERP");
                workService.issuedTest(issuedTest);
                // logMap.put("retCode", issuedTest.get("retCode"));
                //workService.updateErpLog(logMap);
                //消息机制不重新推送反馈ERP，上面对应func已经反馈了
                if ("ERP-101-MSGSTATUS".equals(func) || "ERP-101-RCVMSG".equals(func)) {
                    return responseMsg;
                }
                //2023-05-25 yebo 新增反馈回调ERP，反馈处理结果
                JSONArray fdarrays = new JSONArray();
                JSONObject jsonObject = new JSONObject();
                String msgId = CreatMsgId.getMsgId();
                jsonObject.put("msgId", issuedTest.get("msgId"));
                fdarrays.add(jsonObject);
                //  workService.resultBackToErp(fdarrays, msgId);
                erpBackAsync.resultBackToErpAsync(fdarrays, msgId);
                return responseMsg;
            }
        }
        return responseMsg;
    }
}